﻿namespace Sidvall.WorkItemManager.Data.Model.EntityManagers
{
    public partial class WorkItemManager<TEntity, TList>
    {
        #region GetExecutionTime

        public System.TimeSpan? GetExecutionTime(Sidvall.WorkItemManager.Data.IWorkItem item)
        {
            switch (item.WorkItemStatusId)
            {
                case Sidvall.WorkItemManager.Workflow.WorkItemStatus.Executing:
                    return System.DateTime.UtcNow.Subtract(item.ExecutionStartTime.Value.ToUniversalTime());
                default:
                    return null;
            }
        }

        #endregion
        #region GetIdleTime

        public System.TimeSpan? GetIdleTime(Sidvall.WorkItemManager.Data.IWorkItem item)
        {
            if (item == null)
                return null;
            var latestActivity = GetLatestActivity(item);
            if (latestActivity == null)
                return null;
            return System.DateTime.UtcNow.Subtract(latestActivity.Value.ToUniversalTime());
        }

        #endregion
        #region GetLatestActivity

        public System.DateTime? GetLatestActivity(Sidvall.WorkItemManager.Data.IWorkItem item)
        {
            System.DateTime? time;

            if (item == null)
                return null;
            time = item.ExecutionContextUpdated;
            if (item.ExecutionStartTime != null)
            {
                if ((time == null) || (time < item.ExecutionStartTime))
                    time = item.ExecutionStartTime;
            }
            if (item.LastExecutionEndTime != null)
            {
                if ((time == null) || (time < item.LastExecutionEndTime))
                    time = item.LastExecutionEndTime;
            }
            if (item.LastExecutionStartTime != null)
            {
                if ((time == null) || (time < item.LastExecutionStartTime))
                    time = item.LastExecutionStartTime;
            }
            return time;
        }

        #endregion
    }
}